//
//  HOfilter.m
//  tjp_helper
//
//  Created by Daniel Braun on 29/01/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "HOfilterMult.h"


@implementation HOfilterMult
- (id) init {
	self = [super init];
	if (self != nil) {
	}
	return self;
}
- (void) dealloc {
	[filters release];
	[super dealloc];
}


- (void) setFilters:(NSArray *)a
{
	[filters release];
	filters=[a retain];
}
- (void) setAny:(BOOL)f
{
	any=f;
}

- (BOOL) shouldAccept:(HierarchicalObject *)ho
{
	unsigned int i, count = [filters count];
	for (i = 0; i < count; i++) {
		NSObject  <HierarchicalObjectFiltering>* f = [filters objectAtIndex:i];
		BOOL b=[f shouldAccept:ho];
		if (any && b) return YES;
		if (!any && !b) return NO;
	}
	if (any) return NO;
	else return YES;
}

- (BOOL) shouldRecurse:(HierarchicalObject *)ho
{
	unsigned int i, count = [filters count];
	for (i = 0; i < count; i++) {
		NSObject  <HierarchicalObjectFiltering>* f = [filters objectAtIndex:i];
		BOOL b=[f shouldRecurse:ho];
		if (any && b) return YES;
		if (!any && !b) return NO;
	}
	if (any) return NO;
	else return YES;
}

+ (id) filterMultAny:(BOOL)any filters:(NSArray *)a
{
	HOfilterMult *x=[[[[self class]alloc]init]autorelease];
	[x setAny: any];
	[x setFilters:a];
	return x;
}


@end




@implementation HOfilterIsLeaf 

+ (id) filterIsLeaf
{ 
	HOfilterIsLeaf *f=[[[[self class]alloc]init]autorelease];
	return f;
}
- (BOOL) shouldRecurse:(HierarchicalObject *)ho
{
	return YES;
}
- (BOOL) shouldAccept:(HierarchicalObject *)ho
{
	return [ho isLeaf];
}
@end


@implementation HOfilterIsLevel

- (void) setLevel:(int)l
{
	level=l;
}
- (void) setAllowLower:(hofl_filter_t)f
{
	allowLower=f;
}

+ (id) filterIsLevel:(int)l allowLower:(hofl_filter_t)fal;
{ 
	HOfilterIsLevel *f=[[[[self class]alloc]init]autorelease];
	[f setLevel:l];
	[f setAllowLower:fal];
	return f;
}

- (BOOL) shouldRecurse:(HierarchicalObject *)ho
{
	if ([ho level]>=level) return NO;
	return YES;
}
- (BOOL) shouldAccept:(HierarchicalObject *)ho
{
	int l=[ho level];
	if (l== level) return YES;
	if (l>level) return NO;
	// l<level
	switch (allowLower) {
		case hofl_exact_level:
			return NO;
		case hofl_or_lower:
			return YES;
		case hofl_or_lower_leaf:
			return [ho isLeaf];
		default:
			NSAssert(0, @"bad value for allowLower");
			break;
	}
	return NO;
}
@end




@implementation HOfilterOnKeyValue

- (void) setKey:(NSString *)_key cmp:(NSComparisonResult) _cmp ref:(id)_ref
{
	[key release]; key=[_key retain];
	cmp=_cmp;
	[ref release]; ref=[_ref retain];
}

+ (id) filterOnKeyValue:(NSString *)key op:(NSComparisonResult)cmp ref:(id )d;
{
	HOfilterOnKeyValue *f=[[[HOfilterOnKeyValue alloc]init]autorelease];
	if (!f) return f;
	
	[f setKey:key cmp:cmp ref:d];
	
	return f;
}

- (BOOL) shouldRecurse:(HierarchicalObject *)ho
{
	return YES;
}
- (BOOL) shouldAccept:(HierarchicalObject *)ho
{
	id d=[ho valueForKey:key];
	if (!d) return NO;
	NSComparisonResult r=[d compare:ref];
	if (cmp==r) return YES;
	return NO;
}
@end

